package com.lemon.exam.common.listener;

import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.lemon.exam.common.exception.CustomException;
import com.lemon.exam.entity.dto.PaperExcelDTO;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 试卷读取监听器
 *
 * @author Lemon
 * @since 2025/7/22 14:52
 */
@Slf4j
@Getter
public class PaperReadListener implements ReadListener<PaperExcelDTO> {
    //保存数据
    private final List<PaperExcelDTO> questions = new ArrayList<>();

    @Override
    public void invoke(PaperExcelDTO data, AnalysisContext context) {
        data.setRowIndex(context.readRowHolder().getRowIndex());
        questions.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("读取完成，共读取{}行", context.readRowHolder().getRowIndex());
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("读取Excel行[{}]出错", context.readRowHolder().getRowIndex(), exception);
        throw new CustomException("读取文件失败:%s".formatted(exception.getMessage()));
    }
}
